package org.yuanqiframework.yuanqi.web.auth.service;

import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import org.yuanqiframework.yuanqi.core.constant.Constants;
import org.yuanqiframework.yuanqi.core.utils.AddressUtils;
import org.yuanqiframework.yuanqi.core.utils.StringUtils;
import org.yuanqiframework.yuanqi.web.WebProperty;
import org.yuanqiframework.yuanqi.web.auth.entity.LoginDTO;
import org.yuanqiframework.yuanqi.web.cache.service.ICacheContainer;
import org.yuanqiframework.yuanqi.web.utils.IpUtils;
import org.yuanqiframework.yuanqi.web.utils.ServletUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * token令牌
 *
 * @author cbt28
 */
@Component
public class TokenService {
    @Resource
    private WebProperty webProperty;
    @Resource
    private ICacheContainer container;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    protected static final long MILLIS_MINUTE_TEN = 20 * 60 * MILLIS_SECOND;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginDTO getLoginDTO(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                return (LoginDTO) container.get(userKey);
            } catch (Exception e) {
            }
        }
        return null;
    }

    public LoginDTO getLoginDTO(String token) {
        //去除Token前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        try {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            return (LoginDTO) container.get(userKey);
        } catch (Exception e) {
        }
        return null;
    }


    /**
     * 设置用户身份信息
     */
    public void setLoginDTO(LoginDTO loginDTO) {
        if (StringUtils.isNotNull(loginDTO) && StringUtils.isNotEmpty(loginDTO.getToken())) {
            refreshToken(loginDTO);
        }
    }

    /**
     * 删除用户身份信息
     */
    public Boolean delLoginDTO(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                container.remove(getTokenKey(uuid));
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }

    /**
     * 创建令牌
     *
     * @param loginDTO 用户信息
     * @return 令牌
     */
    public String createToken(LoginDTO loginDTO) {
        String token = UUID.randomUUID().toString().replace("-", "");
        loginDTO.setToken(token);
        setUserAgent(loginDTO);
        refreshToken(loginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginDTO
     * @return 令牌
     */
    public void verifyToken(LoginDTO loginDTO) {
        long expireTime = loginDTO.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginDTO);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginDTO 登录信息
     */
    public void refreshToken(LoginDTO loginDTO) {
        loginDTO.setLoginTime(System.currentTimeMillis());
        loginDTO.setExpireTime(loginDTO.getLoginTime() + webProperty.getTokenExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginDTO缓存
        String userKey = getTokenKey(loginDTO.getToken());
        container.put(userKey, webProperty.getTokenExpireTime(), loginDTO);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginDTO 登录信息
     */
    public void setUserAgent(LoginDTO loginDTO) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginDTO.setIpaddr(ip);
        loginDTO.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginDTO.setBrowser(userAgent.getBrowser().getName());
        loginDTO.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, webProperty.getTokenSecret()).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(webProperty.getTokenSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        //尝试从请求头查找token
        String token = request.getHeader(webProperty.getTokenHeader());
        //若请求头不含有token，则尝试从Session中查找
        if (!StringUtils.isNotEmpty(token)) {
            Object t2 = request.getSession().getAttribute(webProperty.getTokenHeader());
            if (t2 != null) {
                token = t2.toString();
            }
        }
        //去除Token前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return "login_user_tokens:" + uuid;
    }
}
